package com.wmx.thread.synchronize_and_lock;

import java.util.concurrent.locks.ReentrantLock;

/**********************************
 * @author wmx
 * @date 2019/8/21 15:54
 * @description:
 * @version 1.0
 ************************************/
public class MyTryLockTest {
    private static MyTryLock reentrantLock = new MyTryLock();

    public static void main(String[] args) {
        for (int i = 0; i <3 ; i++) {
            new Thread(()->{
                insert();
            }).start();
        }
     /*   try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("===========AtomicInteger========"+reentrantLock.getAtomicInteger().get());*/

    }

    public static void insert(){
        if(reentrantLock.getTryLock()){
            try {
                System.out.println(Thread.currentThread().getName()+"获得锁成功================");
                Thread.sleep(1000); //不加会出现多个线程获得锁 ，加了为什么就不会出现问题(原因是cpu运行太快了,锁已经关闭了).
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                reentrantLock.unLock();
            }
        }else {
            System.out.println(Thread.currentThread().getName()+"获得锁失败================");
        }
    }
}
